import { Timer } from "@sapi-game/gameComponent/common/timer/timer";
import { Game, GameComponent } from "@sapi-game/main";
import { Duration } from "@sapi-game/utils";
import { PillarOfFortuneLobbyState } from "../states/lobby";

export class PillarOfFortuneLobbyStarter extends GameComponent<PillarOfFortuneLobbyState> {
    private readonly MIN_PLAYERS = 2;

    get timer() {
        return this.state.getComponent(Timer);
    }

    override onAttach(): void {
        this.subscribe(
            Game.events.interval,
            () => {
                this.UpdateTimer();
                this.context.players.clearInvalid();
                this.showActionBar();
                // 倒计时结束，开始游戏
                if (this.timer.time === 0) {
                    this.state.start();
                }
            },
            new Duration(10)
        );
    }

    private UpdateTimer() {
        const timer = this.timer;
        const size = this.context.players.validSize;

        // 人数不足时重置计时
        if (size < this.MIN_PLAYERS) {
            if (timer.isRunning) {
                this.context.players.sendMessage("人数不足2人，已取消");
                timer.stop();
                timer.set(this.state.BASE_TIME);
            }
            return;
        }

        // 自动调整倒计时时间
        const targetTime = this.getTargetTime(size);
        if (!timer.isRunning) {
            timer.start();
        } else if (timer.time > targetTime) {
            timer.set(targetTime);
        }
    }

    /** 根据人数决定倒计时目标 */
    private getTargetTime(size: number): number {
        if (size >= 6) return 15;
        if (size >= 4) return 20;
        return this.state.BASE_TIME;
    }

    /** 显示倒计时或等待提示 */
    private showActionBar() {
        const timer = this.timer;
        const text =
            this.context.players.validSize >= this.MIN_PLAYERS
                ? timer.time.toString()
                : "§a等待中...";
        this.context.players.actionbar(text);
    }
}
